<?php

namespace app\api\controller;

use app\api\service\ArticleService;
use app\api\service\GoodsService;
use app\api\service\UserService;
use app\common\controller\Api;
use app\common\model\Category;
use app\common\model\UserShareImage;
use app\sapi\service\WxPayNotify;
use think\Cache;
use think\Db;
use think\Config;
use wechat\Wechat;
use app\common\model\User;
use app\common\model\UserLuckdrawLog;

/**
 * 首页接口
 */
class Index extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    /**
     * 首页
     *
     */
    public function index()
    {
        $this->success('请求成功');
    }


    public function notify(WxPayNotify $notify)
    {
        $notify->Handle(false);
    }

    public function messageids()
    {
        $str = '{
            "groupon_success": "w1ZV0qgXC0y1F-PcJvu8zaOtz-v6G6HTXylBpEJ8s5g",
            "groupon_fail": "mj6jxk2hE-hl9RKjOMlL6l0S9vlYo11SeHHKZh8e838",
            "order_sended": "z1VKS8ffkJQiv5lKuhGWHtNwGZdGzlExKonoAu5WP2w",
            "refund_agree": "TwvQBBNT1CC6tXJzQaNcHn4DvfJyULqti8Ln7ORNiYA",
            "aftersale_change": "WakEb7VImU5hqnngs4BCzZx_p0YycSBwYLG77szIUJA",
            "wallet_apply": "EHyOavaH4dYUZ1skeGIYlh8tjin3LJ4XIfJtRLZ1-4A",
            "wallet_change": "uhqO8rkuH3D-6VLqiuDpc6E-clRwqQcyZLgrqJTaqGs",
            "score_change": "0q4wiOduQHw87C1nhSQjE4QLyCzW4rFb91MVRHitdME",
            "store_order_new": "OID0zBivL_sYaq0IxIHyZ08HVRo_oiunDJDyCchHJVg",
            "store_apply": "FIcSI2G9QhVOT-vaGJBYXbWT005jH6Vn3Vw_FoPlvKk"
        }';
        $data = json_decode($str, true);
        $this->success('初始化数据', $data);
    }

    public function asyncPages()
    {
        $this->success('同步路由成功');
    }

    public function richtext(ArticleService $articleService)
    {
        $id = input('id/d', 1);
        $res = $articleService->getArticleList(18, 1, 1);
        if ($res['total'] <= 0) $this->error('关于我们未设置');
        $this->success('', $res['data'][0]);
    }

    /**
     * 上传图片到oss
     */
    public function upload()
    {
        $pdir = 'front/'.date('Ymd').'/';
        if(!isset($_FILES['file']) || !$_FILES['file'] || $_FILES['file']['error']){
            $this->error('上传出错');
        }
        if ($_FILES['file']['size']>10485760) {
            $this->error('上传文件过大');
        }
        $extension = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
        // \think\Log::write('上传文件名称：'.$_FILES['file']['name']);
        if(!in_array($extension,['jpg','jpeg','JPG','JPEG','png','PNG','gif','mp4'])){
            $this->error('上传格式不允许');
        }
        $file = file_get_contents($_FILES['file']["tmp_name"]);
        $ossService = new \services\OssService();
        /*@todo img*/
        $filename = md5($_FILES['file']['name'].date('YmdHi').rand(1000,9999)).'.'.$extension;
        $upload_file=$ossService->upload_file_content($file,$pdir.$filename);
        if ($upload_file) {
            \think\Log::write('upload:'.$filename);
            $this->success('上传成功', ['url' => '/' . $pdir.$filename,'upload_domain'=>config('upload_domain')]);
        } else {
            $this->error('上传出错');
        }
    }

    public function jssdk()
    {
        $url = urldecode(input('uri', ''));
        $config = Config::get('msxgzh');
        $wecaht = new Wechat($config['appid'], $config['appsecret']);
        $data = $wecaht->creatSign($url);
        $data['debug'] = Config::get('app_debug');
        $data['debug'] = false;
        $data['jsApiList'] = [
            'checkJsApi', //判断当前客户端版本是否支持指定JS接口
//            'onMenuShareAppMessage', //分享接口
            'updateAppMessageShareData',
            'updateTimelineShareData',
            'getLocation', //获取位置
            'openLocation', //打开位置
            /*'scanQRCode', //扫一扫接口
            'chooseWXPay', //微信支付
            'chooseImage', //拍照或从手机相册中选图接口
            'previewImage', //预览图片接口
            'uploadImage' //上传图片*/
        ];
        $data['openTagList'] = ['wx-open-launch-weapp'];
        $this->success('', $data);
    }

    /**
     * unipush参数，企业微信参数
     * @DateTime 2023-04-21T11:46:02+0800
     * @return   [type]                   [description]
     */
    public function pushParam()
    {
        if (!isset($this->auth->id) || !$this->auth->id) {
            $this->error('请先登录');
        }
        $cid = input('cid','','htmlspecialchars');
        if (!$cid) {
            $this->error('参数有误');
        }
        $user = User::get($this->auth->id);
        $user->birthday = $cid;
        $user->save();
        $this->success('成功');
    }


    public function qywx()
    {
        $this->success('',config('qywx'));
    }


    public function xcxlink()
    {
        $data = [
            'elem'=>'commercialize/pages/taoke-guide/index?scene=e49a3142a6f2424db4097f5516450e20',
            // 'elem'=>'/ele-estore/ele-takeout-index/ele-takeout-index.html?shopId=E18047027597300779596',
            // 'meituan'=>'pages/restaurant/restaurant.html?poi_id=3553104913&from=from_share_restaurant',
            'meituan'=>'/index/pages/h5/h5?f_userId=1&f_token=1&s_cps=1&weburl=https%3A%2F%2Fdpurl.cn%2FXfKj3izz',
            'meituanwm'=>'/index/pages/h5/h5?f_userId=1&f_token=1&s_cps=1&weburl=https%3A%2F%2Fdpurl.cn%2FXfKj3izz',
            'elem_gf'=>'commercialize/pages/compose-reduce-guide/index.html?startTime=1683904912349&spm_url=a2ogi.27842964&scene=fafa08ba6c1f4ddba74e60ff698b8126&configKey=BDLM_ELE_WECHAT_COMPONSE_REDUCE_GUIDE&spm=a2ogi.27842964.undefined'
        ];
        $this->success('',$data);
    }


    public function version()
    {
        $type = input('type','android');
        $version = Db::name('version')->where(['type'=>$type])->order('id DESC')->find();
        if ($version) {
            $version['downloadurl'] = config('upload_domain').$version['downloadurl'];
        }
        $this->success('最新版本',$version);
    }



    public function push()
    {
        $promotion_id = 'yz-68197110-145818-170907';
        $telephone = '15395101520';
        $bwc = new \services\BwcService();
        $res = $bwc->merchantList(31.251041,121.460161,'76ee637b-badb-4a1f-a943-5a6d22de862a');
        var_dump($res);exit;
        // $decode = json_decode($res,1);
        // if (isset($decode['data']['poiList'][0])) {
        //     $data = $decode['data']['poiList'][0];
        $data['wmPoiId'] = 'vG%2Fl2HuGSytF7JIrn0VGrw%3D%3D';
        $data['poiEventId'] = '1357916971';
        $decode['data']['meituanPvId'] = '9d90630c-ecdd-4593-8896-b84f81b476b7';
            // $res = $bwc->registerevent($data['wmPoiId'],$data['poiEventId'],$decode['data']['meituanPvId'],$telephone,$promotion_id);
            // var_dump($res);exit;
        $userEventId = 'KST5DtIkbOzqeGiSx0ufbg==';
        // $res = $bwc->cancelevent($userEventId);
        $platform_order_no = '';
        $query_type = 1;
        // $start_time = date('Y-m-d').' 00:00:00';
        // $end_time = date('Y-m-d H:i:s');
        $start_time = date('Y-m-d',(time()-86400)).' 00:00:00';
        $end_time = date('Y-m-d').' 00:00:00';
        $page = 1;
        $res = $bwc->orderList($platform_order_no,$query_type,$start_time,$end_time,$page);
        var_dump($res);exit;
        // }
        // $Wechat = new \wechat\Wechat();
        // $touser = 'oioAF6aHTu2RMH6uQPtIJY5bf2n8';
        // $msg = [];
        // $msg['first'] = '订单审核通过';
        // $msg['keyword1'] = '111';
        // $msg['keyword2'] = '已完成';
        // $msg['keyword3'] = '20230624';
        // $msg['remark'] = '111';
        // $template_id = 'MJq3lKrIkbzsH_OO2rWtDHbb9G07h-foArLAa5n7XCo';
        // $res = $Wechat->sendTplMsg($touser, $msg, $template_id, $url = '', $color = '#FF683F');
        $cid = input('cid','');
        $lPublics = new \app\api\service\UserService();
        $res = $lPublics->pushChat($cid,'返佣提醒','您推荐的用户产生了一笔收益，请查看','/pages/index/index');
        // $external_userid = 'wmRQHTPgAAJPketJCBmK3xWIhubu-WLg';
        // $sender = 'wangzhe';
        // $title = '您的活动订单审核被驳回啦';
        // $picurl = config('upload_domain').'/uploads/20230422/baca91c2f33a6d1270aae65ea4d3dc79.png';
        // $desc = '点击查看驳回原因';
        // $url = config('h5_domain').'/pages/index/order';
        // $res = $lPublics->qywxPush($external_userid,$sender,$title,$picurl,$desc,$url);
        // var_dump($res);exit;
        // $Alisms = new \addons\alisms\Alisms();
        // $params = [
        //     'mobile' => '15395101520',
        //     'event' => 'order_timeout',
        //     'msg' => '您好，您在吃喝不愁平台参加的外卖活动订单即将超时，请尽快去平台提交。',
        // ];
        // $res = $Alisms->smsNotice($params);
        var_dump($res);exit;
    }




    /**
     * 接收企业微信客户变更事件
     * @DateTime 2023-05-06T13:20:53+0800
     * @return   [type]                   [description]
     */
    public function receive()
    {
        include_once ROOT_PATH."extend/weworkapi/callback/WXBizMsgCrypt.php";
        include_once ROOT_PATH."extend/weworkapi/api/src/CorpAPI.class.php";
        $token = config('qywx.token');
        //就是第一步图中的EncodingAESKey
        $encodingAESKey = config('qywx.encodingAESKey');
        //企业微信corpid,前往我的企业->企业ID 内查看
        $corpid= config('qywx.corpid');
        $corpsecret= config('qywx.secret');
        $wxcpt = new \WXBizMsgCrypt($token, $encodingAESKey, $corpid);
        $sReqData = file_get_contents("php://input");
        $sReqMsgSig = $_GET['msg_signature'];
        $sReqTimeStamp = $_GET['timestamp'];
        $sReqNonce = $_GET['nonce'];
        $content = json_encode($_GET);
        $sMsg = "";  // 解析之后的明文
        $errCode = $wxcpt->DecryptMsg($sReqMsgSig, $sReqTimeStamp, $sReqNonce, $sReqData, $sMsg);
        \think\Log::write('企业微信添加客服消息:'.$sMsg);
        if ($errCode==0) {
            Db::startTrans();
            try {
            //<xml>
            //<ToUserName><![CDATA[wwfad5d2bae51a9015]]></ToUserName>
            //<FromUserName><![CDATA[sys]]></FromUserName>
            //<CreateTime>1683355721</CreateTime>
            //<MsgType><![CDATA[event]]></MsgType>
            //<Event><![CDATA[change_external_contact]]></Event>
            //<ChangeType><![CDATA[add_external_contact]]></ChangeType>
            //<UserID><![CDATA[wangzhe]]></UserID>
            //<ExternalUserID><![CDATA[wmRQHTPgAAEnXdidPaX_Xnx1GfLTjXow]]></ExternalUserID>
            //</xml>
                $SimpleXMLElement = new \SimpleXMLElement($sMsg);
                $ExternalUserID = strval($SimpleXMLElement->ExternalUserID);
                $ToUserName = strval($SimpleXMLElement->ToUserName);
                $FromUserName = strval($SimpleXMLElement->FromUserName);//发送消息的人
                $CreateTime = strval($SimpleXMLElement->CreateTime);
                $Event = strval($SimpleXMLElement->Event);
                $ChangeType = strval($SimpleXMLElement->ChangeType);
                $UserID = strval($SimpleXMLElement->UserID);
                if ($ChangeType=='add_external_contact') {
                    $api = new \CorpAPI($corpid, $corpsecret);
                    $token = $api->obtainAccessToken();
                    $res = file_get_contents('https://qyapi.weixin.qq.com/cgi-bin/externalcontact/get?access_token='.$token.'&external_userid='.$ExternalUserID);
                    \think\Log::write('企业微信添加客服个人信息:'.$res);
                    // {"errcode":0,"errmsg":"ok","external_contact":{"external_userid":"wmRQHTPgAAEnXdidPaX_Xnx1GfLTjXow","name":"Hovm","type":1,"avatar":"http://wx.qlogo.cn/mmhead/Q3auHgzwzM6PxVcINQndI9gTCAce8Pklwx3udU7BR6NSnxeavy6cXw/0","gender":1,"unionid":"oC_s562vgMPLsOmcOzZxGBZ3tozM"},"follow_user":[{"userid":"wangzhe","remark":"Hovm","description":"","createtime":1683349097,"tags":[],"remark_mobiles":[],"add_way":1,"oper_userid":"wmRQHTPgAAEnXdidPaX_Xnx1GfLTjXow"}]}
                    $result = json_decode($res,1);
                    $unionid = '';
                    if (isset($result['external_contact']['unionid'])) {
                        $unionid = $result['external_contact']['unionid'];
                    }
                    $user = Db::name('user')->field('id')->where(['user_type'=>2,'unionid'=>$unionid])->find();
                    $user_id = 0;
                    if (isset($user['id'])) {
                        $user_id = $user['id'];
                    }
                    Db::name('qywx_receive')->insert([
                        'content' => $content,
                        'xml' => $sReqData,
                        'ExternalUserID' => $ExternalUserID,
                        'ToUserName' => $ToUserName,
                        'FromUserName' => $FromUserName,
                        'CreateTime' => $CreateTime,
                        'Event' => $Event,
                        'ChangeType' => $ChangeType,
                        'UserID' => $UserID,
                        'info' => $res,
                        'unionid' => $unionid,
                        'user_id' => $user_id,
                    ]);
                    // 会员任务和会员等级
                    if ($user_id) {
                        $UserService = new UserService();
                        $return = $UserService->oneLevel($user_id);
                        if (!$return) {
                            Db::rollback();
                            $this->error('更新会员等级失败');
                        }
                    }
                }
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                $this->error('更新会员等级失败');
            }
        }
    }


    public function receive1()
    {//就是第一步图中的token
        $token = 'PUlwOFEThMUv2LPAmo';
        //就是第一步图中的EncodingAESKey
        $encodingAESKey = 'XzbxvhtQu4KBCmJYs34YS58l3fDDe33C3nJInLuNMNu';
        //企业微信corpid,前往我的企业->企业ID 内查看
        $receiveid= 'wwfad5d2bae51a9015';
        
        $signature = $_GET['msg_signature'];

        $timestamp = $_GET['timestamp'];

        $echostr = $_GET['echostr'];

        $nonce = $_GET['nonce'];



        $key = base64_decode($encodingAESKey . '=');

        $iv = substr($key, 0, 16);

        $array = array($echostr, $token, $timestamp, $nonce);

        sort($array, SORT_STRING);

        $str = implode($array);

        $decryptSignature = sha1($str);

        if ($signature != $decryptSignature){

            return false;

        }

        $decrypted = openssl_decrypt($echostr, 'AES-256-CBC', $key, OPENSSL_ZERO_PADDING,$iv);

        $pad = ord(substr($decrypted, -1));

        $result = substr($decrypted, 0, (strlen($decrypted) - $pad));

        //拆分

        $content = substr($result, 16, strlen($result));

        $len_list = unpack('N', substr($content, 0, 4));

        $xml_len = $len_list[1];

        $xml_content = substr($content, 4, $xml_len);
        
        $from_receiveId = substr($content, $xml_len+ 4);
        if($from_receiveId  != $receiveid){
                return false;
        }
        //返回验证内容

        echo $xml_content;
    }

    public function init()
    {
        if (isset($this->auth->id) && $this->auth->id) {
            $equipment_code = input('equipment_code','','htmlspecialchars');
            $user = User::get($this->auth->id);
            $user->equipment_code = $equipment_code;
            $user->save();
        }
        
        $xcxlink = [
            // 'elem'=>'commercialize/pages/taoke-guide/index?scene=e49a3142a6f2424db4097f5516450e20',
            // 'meituan'=>'/index/pages/h5/h5?f_userId=1&f_token=1&s_cps=1&weburl=https%3A%2F%2Fdpurl.cn%2FXfKj3izz',
            // 'elem'=>'commercialize/pages/taoke-guide/index?scene=3ca706d85ce74b9c93ebc31473dc6880',//领红包
            'elem'=>'commercialize/pages/taoke-guide/index?scene=d3312f8675d043a4987adddde98c591f',
            'meituan'=>'/index/pages/h5/h5?weburl=https%3A%2F%2Fclick.meituan.com%2Ft%3Ft%3D1%26c%3D2%26p%3DXA9U5r5zjQqe',//美团领红包
            'meituanwm'=>'/index/pages/h5/h5?f_userId=1&f_token=1&s_cps=1&weburl=https%3A%2F%2Fdpurl.cn%2FXfKj3izz',
            'elem_gf'=>'commercialize/pages/compose-reduce-guide/index?scene=49c5853cfc2c49c4b2e46893c66bd1a4'
        ];

        $ArticleModel = new \app\common\model\Article();
        $banner = $ArticleModel->where(['status'=>'normal','type'=>3])->select();

        $data = [
            'wechat' =>
            [
                'appid' => config('wx_gzh.appid'),
                'autologin' => true,
                'redirecturl' => config('h5_domain'),
                'redirecturi' => config('domain').'/index/index/authredirect',
            ],
            'shop_redirect' => [
                'meituan' => 'pages/restaurant/restaurant.html?from=from_share_restaurant&poi_id=',
                'elem' => '/ele-estore/ele-takeout-index/ele-takeout-index.html?shopId=',
            ],
            'share' => [
                'homepage' => ['title'=>'全城外卖试吃，就上吃喝不愁','desc'=>'美团/饿了么商家的20000+份霸王餐等你来领~','image'=>'https://oss.chbcplus.com/uploads/20230422/baca91c2f33a6d1270aae65ea4d3dc79.png','path'=>config('share_domain').'/#/'],
                'playinfo' => ['title'=>'XXXXX店铺外卖福利','desc'=>'最低只需XX元','image'=>''],
            ],
            'qywx' => config('qywx'),
            'xcxlink' => $xcxlink,
            'banner' => $banner,
            'guide'=>[
                'video' => 'https://oss.chbcplus.com/9ba443f4a9467ecd65c68525a8e1a9e0.mp4',
                'img' => 'https://oss.chbcplus.com/images/xszy.jpg'
            ],
            'shop' => [
                'user_protocol' => 5,
                'privacy_protocol' => 7,
            ],
            'member_domain' => config('member_domain').'/#/',
            'dwqx' => 1,
            'isIoslogin' => $this->isIosLogin(),
            'hwdw' => 1,
            'elem_gf' => [
                'appid' => 'wxece3a9a4c82f58c9',
                'path' => 'commercialize/pages/compose-reduce-guide/index?scene=2d1ea41383dc47b4a4d9c91e49337daa'
            ],
            'expire' => '次日24点', // 美团官方订单的评价截止时间
            'env_https' => config('h5_domain').'/#/',
            'MAP_KEY' => '486e1ed8066d2de1fcf7843095dbe02d',
        ];
        $this->success('初始化数据', $data);
    }

    public function isIosLogin()
    {
        return 1;
    }


    /**
     * 饿了么官方
     * @DateTime 2023-05-15T18:02:50+0800
     * @return   [type]                   [description]
     */
    public function elmShopList()
    {
        $longitude = input('longitude','');
        $latitude = input('latitude','');
        // $longitude = '120.135018';
        // $latitude = '30.257318';
        if (!$latitude || !$longitude) {
            $this->error('请授权位置信息');
        }
        $Obj = new \services\ElemService();
        $param['longitude'] = $longitude;
        $param['latitude'] = $latitude;
        $param['recall_overlay_coupon'] = true;
        // $param['media_activity_id'] = '2156054';
        // $param['in_activity'] = true;
        // $param['filter_has_overlay_coupon'] = true;
        // $param['has_bonus_stock'] = true;
        $param['sort_type'] = 'couponAmount';
        $res = $Obj->getShopList($param);
        // var_dump($res);exit;
        $res = json_decode($res,1);
        $data = [];
        if (isset($res['alibaba_alsc_union_eleme_promotion_storepromotion_query_response']['data']['records']['store_promotion_dto']) && $res['alibaba_alsc_union_eleme_promotion_storepromotion_query_response']['data']['records']['store_promotion_dto']) {
          foreach ($res['alibaba_alsc_union_eleme_promotion_storepromotion_query_response']['data']['records']['store_promotion_dto'] as $key => $value) {
            $data[$key]['indistinct_monthly_sales'] = $value['indistinct_monthly_sales'];
            $data[$key]['link'] = $value['link'];
            $data[$key]['shop_logo'] = $value['shop_logo'];
            $data[$key]['title'] = $value['title'];
            $data[$key]['amount'] = 0;
            if (isset($value['overlay_coupon']['amount']) && $value['overlay_coupon']['amount']) {
              $data[$key]['amount'] = $value['overlay_coupon']['amount'];
            }
          }
        }
        $this->success('饿了么官方',$data);
    }


    public function debugLog()
    {
        $params = $this->request->param();
        if (isset($params['token']) && $params['token']) {
            $data = \app\common\library\Token::get($params['token']);
            if (isset($data['user_id'])) {
                $user_id = intval($data['user_id']);
                $params['userid'] = $user_id;
            }
        }
        \think\Log::write('app微信授权报错'.json_encode($params,JSON_UNESCAPED_UNICODE));
    }
}
